#include "kernel.h"
//#include "LPC17xx.h"
#include "heap.h"

OSStackType IdleStack[IDLE_STACK_SIZE];

uint_32 criticalNesting = 0; 
uint_32 interruptNesting = 0;
uint_32 idleCounter = 0;

void uKern_Init(void)
{
	
	tasksInit();
	idleTaskInit();
	heapInit();
	OSTickConfig();
}

void StartOS(void){
	FindHighestPriorityTask();
	currentTCB = highestTCB;
	OSTickStart();
	start_os();
	
}

void interruptEnter(void)
{
	ENTER_CRITICAL();
	interruptNesting++;
	EXIT_CRITICAL();
}

void interruptExit(void)
{
	ENTER_CRITICAL();
		
	if(--interruptNesting == 0){
		FindHighestPriorityTask();
		if (highestTCB != currentTCB)
			SWITCH_CONTEXT();

		
	}
	EXIT_CRITICAL();
}

void IdleTask(void *args)
{
	while(1){
		ENTER_CRITICAL();
		idleCounter++;
		EXIT_CRITICAL();
#if IDLE_TASK_SLEEP
		LPC_SC->PCON = 0x00;
		__WFI();
#endif
#if HOOKS_ENABLED && IDLE_TASK_HOOK 
		idleTaskHook();
#endif
	}
}

void idleTaskInit()
{
#if STACK_GROWTH == 1
	task_create(IDLE_TASK_PRIO, IdleTask, NULL, IDLE_STACK_SIZE, &IdleStack[IDLE_STACK_SIZE - 1]);
#else 
	task_create(IDLE_TASK_PRIO, IdleTask, NULL, IDLE_STACK_SIZE, &ildeStack[0]);
#endif
}
